<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('channel.name')" prop="name">
          <el-input v-model="formSearch.name" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button :icon="Search" type="primary" @click="handleSearch">{{
            t("common.searchButton")
          }}</el-button>
          <el-button :icon="RefreshLeft" @click="handleResetFields">{{
            t("common.resetButton")
          }}</el-button>
          <search-input-expland
            @on-expland-change="(v:boolean)=>{ searchInputExpland=v}"
            visibility="hidden"
          ></search-input-expland>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-channel-grid"
    row-key="articleId"
    defaultSort="ascending"
    defaultSortBy="levelCode"
    :request="handleLoadGrid"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <el-button size="mini" type="primary" :icon="Plus" @click="handleAdd">{{
        t("channel.newChannel")
      }}</el-button>
    </template>

    <template #homeMenu="slotProps">
      <el-tag size="small" v-if="slotProps.row.homeMenu == 0" type="warning">
        {{ t("common.false") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.homeMenu == 1">
        {{ t("common.true") }}</el-tag
      >
    </template>
    <template #featuredChannel="slotProps">
      <el-tag
        size="small"
        v-if="slotProps.row.featuredChannel == 0"
        type="warning"
      >
        {{ t("common.false") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.featuredChannel == 1">
        {{ t("common.true") }}</el-tag
      >
    </template>
    <template #singleChannel="slotProps">
      <el-tag
        size="small"
        v-if="slotProps.row.singleChannel == 0"
        type="warning"
      >
        {{ t("common.false") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.singleChannel == 1">
        {{ t("common.true") }}</el-tag
      >
    </template>

    <template #status="slotProps">
      <el-tag size="small" v-if="slotProps.row.status == 0" type="warning">
        {{ t("channel.statusDisabled") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.status == 1">
        {{ t("channel.statusEnabled") }}</el-tag
      >
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
    <template #operate="slotProps">
      <el-link type="primary" @click="handleEdit(slotProps.row)">{{
        t("common.editButton")
      }}</el-link>
      &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row)"
        >{{ t("common.deleteButton") }}
      </el-link>
    </template>
  </data-grid>

  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import SearchInputExpland from "@/components/SearchInputExpland.vue";
import { Plus, Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../utils/utils";
import apiCms from "../api/cms";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

// 查询区域表单数据
const formSearch = reactive({
  name: "",
});

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: () => t("channel.levelCode"),
      field: "levelCode",
      sortable: true,
      resizable: true,
      width: 300,
    },
    {
      title: () => t("channel.name"),
      field: "name",
      sortable: false,
      resizable: true,
      width: 250,
    },
    {
      title: () => t("channel.homeMenu"),
      field: "homeMenu",
      sortable: true,
      resizable: true,
      tdSlot: "homeMenu",
      width: 150,
    },
    {
      title: () => t("channel.featuredChannel"),
      field: "featuredChannel",
      sortable: true,
      resizable: true,
      tdSlot: "featuredChannel",
      width: 180,
    },
    {
      title: () => t("channel.singleChannel"),
      field: "singleChannel",
      sortable: true,
      resizable: true,
      tdSlot: "singleChannel",
      width: 180,
    },
    {
      title: () => t("channel.status"),
      field: "status",
      sortable: true,
      resizable: true,
      tdSlot: "status",
      width: 150,
    },
    {
      title: () => t("channel.description"),
      field: "description",
      sortable: false,
      resizable: true,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiCms
    .queryChannelListing(params)
    .then((response: any) => {
      data = response.data;
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
  // 返回数据给表格组件
  return data;
};

// 删除操作事件
const handleDelete = (row: any) => {
  // 从表格每行右侧链接点击触发的情况
  ElMessageBox.confirm(t("channel.confirmDelete", { name: row.name }), {
    confirmButtonText: t("common.okButton"),
    cancelButtonText: t("common.cancelButton"),
  })
    .then(() => {
      apiCms
        .deleteChannel(row.channelId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            utils.infoNotification(t("channel.deleted", { name: row.name }));
          }
        })
        .catch((err: any) => {
          utils.errorNotification(t("common.submitException"), err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开编辑页
const handleEdit = async (row: any) => {
  editFormRef.value.show(row);
};
// 新增、编辑页确定按钮操作成功回调事件
const onSubmitSuccess = (row: any) => {
  handleSearch();
};
// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
const handleResetFields = () => {
  formSearchRef.value.resetFields();
};
</script>
<style></style>
